import React from 'react';
import {Spin, Card, Row, Col, Table, Form, Button, message as msg} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, DATE_FORMAT} from '../constants';
import {injectIntl} from './intl';
import {conventEnumValueToString, formatDateTime, formatAmount, formatPercent} from '../utils';
import Return from '../common/Return';
import {getDetail} from './api';
import {partClaimType, currency, partClaimReasonStatus, partPaymentMethod, partClaimResultStatus, isYesNo} from '../Enum';
import styles from './style.css';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import FileUpload from './FileUpload';
const FormItem = Form.Item;
const EMPTY_ARRAY = [];

class ConfirmPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        details: [],
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        if(this.props.id)
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            isFetching: false,
                            data: res.data,
                            details: res.data.partClaimReportDetail
                        });
                    else
                        this.setState(({
                            isFetching: false
                        }));
                });
    }
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = data.attachments || [];
        attachments.splice(index, 1);
        if(!this.state.hasOperat)
            this.setState({
                data: {
                    ...data,
                    attachments
                },
                hasOperat: true,
            });
    }
    onChangeUpload = value => {
        const data = this.state.data;
        const attachments = data.attachments || [];
        attachments.push(value[0]);
        if(!this.state.hasOperat)
            this.setState({
                data: {
                    ...data,
                    attachments
                },
                hasOperat: true,
            });
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmitConfirm = () => {
        const {data} = this.state;
        this.setState({loading: true});
        this.props.onSubmitConfirm(data).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, loading} = this.state;
        const submitable = !hasPermissions(PERMISSION.confirm, this.props.permissions);
        let claimFee = 0;
        let claimAmount = 0;
        if(details.length > 0)
            details.forEach(v => {
                claimFee += v.totalAmount;
                claimAmount += v.claimAmount;
            });
        const colums = [{
            title: formatMessage({
                id: 'confirmPanel.column.packingListCode',
                defaultMessage: '箱单号'
            }),
            dataIndex: 'packingListCode',
        }, {
            title: formatMessage({
                id: 'confirmPanel.column.partSaleOrderCode',
                defaultMessage: '备件销售订单编号'
            }),
            dataIndex: 'partSaleOrderCode',
        }, {
            title: formatMessage({
                id: 'confirmPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'confirmPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'confirmPanel.column.claimAmount',
                defaultMessage: '索赔数量'
            }),
            dataIndex: 'claimAmount',
        }, {
            title: formatMessage({
                id: 'confirmPanel.column.price',
                defaultMessage: '备件单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'confirmPanel.column.claimFee',
                defaultMessage: '索赔金额'
            }),
            dataIndex: 'claimFee',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'confirmPanel.column.fobAmount',
                defaultMessage: 'FOB金额'
            }),
            dataIndex: 'fobAmount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'confirmPanel.column.mgmtFee',
                defaultMessage: '管理费'
            }),
            dataIndex: 'mgmtFee',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'confirmPanel.column.totalAmount',
                defaultMessage: '总金额'
            }),
            dataIndex: 'totalAmount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'confirmPanel.column.claimReason',
                defaultMessage: '索赔原因'
            }),
            dataIndex: 'claimReason',
            render: text => conventEnumValueToString(partClaimReasonStatus, text)
        }, {
            title: formatMessage({
                id: 'confirmPanel.column.claimResult',
                defaultMessage: '索赔结果'
            }),
            dataIndex: 'claimResult',
            render: text => conventEnumValueToString(partClaimResultStatus, text)
        }, {
            title: formatMessage({
                id: 'confirmPanel.column.payAmount',
                defaultMessage: '赔付金额'
            }),
            dataIndex: 'payAmount',
            render: text => formatAmount(text)
        }
        ];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'confirmPanel.column.common',
                        defaultMessage: '订单基本信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirmPanel.operation.code',
                                        defaultMessage: '编号'
                                    })}
                                    {...FORM_OPTIONS.item} >
                                        {data.code || '尚未生成'}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'confirmPanel.operation.brandId',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {`(${data.brandCode})${data.brandName}`}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {(data.dealerCode) + data.dealerName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirmPanel.operation.partClaimCode',
                                        defaultMessage: '备件索赔单编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.claimCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'confirmPanel.operation.claimType',
                                            defaultMessage: '索赔类型'
                                        })}
                                        {...FORM_OPTIONS.item}> 
                                        {conventEnumValueToString(partClaimType, data.claimType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirmPanel.operation.invoiceCode',
                                        defaultMessage: '发票号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.invoiceCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'confirmPanel.form.invoicedDate',
                                            defaultMessage: '开票日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.invoicedDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'confirmPanel.operation.currency',
                                            defaultMessage: '币种'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(currency, data.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'confirmPanel.operation.paymentMethod',
                                            defaultMessage: '赔付方式'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(partPaymentMethod, data.paymentMethod)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'confirmPanel.form.receiptDate',
                                            defaultMessage: '收货日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.receiptDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'confirmPanel.form.shipmentDate',
                                            defaultMessage: '出运日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.shipmentDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'confirmPanel.form.actualArrivalDate',
                                            defaultMessage: '到达日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.actualArrivalDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirmPanel.operation.address',
                                        defaultMessage: '地址'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.address}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirmPanel.operation.contactNumber',
                                        defaultMessage: '联系电话'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.contactNumber}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirmPanel.operation.destination',
                                        defaultMessage: '目的地'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.destination}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirmPanel.operation.claimAmount',
                                        defaultMessage: '索赔总数量'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.claimAmount}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.form.isMgmFee',
                                        defaultMessage: '是否需要管理费'
                                    })}{...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(isYesNo, data.paymentMethod === 1 ? 1 : 0)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirmPanel.operation.mgmtRate',
                                        defaultMessage: '管理费率'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.isMgmFee ? formatPercent(data.mgmtRate) : 0}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'confirmPanel.form.createTime',
                                            defaultMessage: '申请日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.createTime, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirmPanel.operation.totalFee',
                                        defaultMessage: '索赔总金额'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatAmount(claimFee)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'confirmPanel.operation.surveyResults',
                                            defaultMessage: '调查结果'
                                        })} {...FORM_OPTIONS.item}>
                                        {data.surveyResults}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'confirmPanel.operation.preventMeasures',
                                            defaultMessage: '预防措施'
                                        })} {...FORM_OPTIONS.item}>
                                        {data.preventMeasures}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'confirmPanel.operation.treatmentScheme',
                                            defaultMessage: '处理方案'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(partClaimResultStatus, data.treatmentScheme)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'confirmPanel.operation.payType',
                                            defaultMessage: '支付方式'
                                        })} {...FORM_OPTIONS.item}>
                                        {data.payType}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'confirmPanel.operation.detail',
                            defaultMessage: '订单清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            columns={colums}
                            rowKey="partId"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card title={formatMessage({
                        id: 'reportPanel.title.files',
                        defaultMessage: '附件清单'
                    })}>
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FileUpload onChange={this.onChangeUpload}
                                    onRemove={this.removeFilePath}
                                    fileList={data.attachments || EMPTY_ARRAY}/>
                            </Col>
                        </Row>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmitConfirm}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'confirmPanel.operation.onSubmitConfirm',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

ConfirmPanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    enterprise: PropTypes.object,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onConfirm
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);

const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getEnterprise = selectorFactory(['page', 'domainData', 'initData', 'enterprise']);
const mapStateToProps = (state, props) => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    permissions: getPermissions(state),
    initEnum: getinitEnumData(state),
    enterprise: getEnterprise(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmitConfirm: data => dispatch(onConfirm(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ConfirmPanel));
